import router from '@/router'
import {post} from '@/util/request'
import {getAddress} from '@/plugin/Map/Mapaddress'
import moment       from 'moment'

export default {
	namespace:'alarmList',
	namespaced:true,
	state:{
		isLoading:false,
		pageData:{}
	},
	mutations:{
		changeLoading(state,v){
			state.isLoading = v;
		},
		changePagedata(state,v){
			state.pageData = v;
		}
	},
	actions:{
		async reload({commit}, data) {
			commit('changeLoading',true);
			let res = await post('/early/warn/list',data);
			let adds = await getAddress(res.data.data.thisPageElements.map(v=>[v.lng,v.lat]));
      res.data.data.thisPageElements.forEach((v,i) => {
        let alarmTypeStr = '';
        switch (Number.parseInt(v.type)) {
          case 1: alarmTypeStr = '急加速'; break;
          case 2: alarmTypeStr = '急减速'; break;
					case 3: alarmTypeStr = '左转弯'; break;
          case 4: alarmTypeStr = '右转弯'; break;
          case 5: alarmTypeStr = '超速'; break;
          case 6: alarmTypeStr = '疲劳驾驶'; break;
        }
        v.alarmTypeStr = alarmTypeStr;
        v.address = adds[i] ? adds[i].formattedAddress : '--';
				v.startTimeStr = moment(v.startTime).format('YYYY-MM-DD HH:mm:ss')
      });
			commit('changePagedata',res.data.data);
			commit('changeLoading',false);
		},
		getAddress({commit},[lng,lat]){
			return getAddress([[lng,lat]]).then(res => {
				return res;
			});
		}
	},
	subscriptions({dispatch},router){
		//给路由加监听一旦进入module绑定的页面时dispatch初始化action
		router.afterEach((to,from)=>{
			if(to.name === this.namespace){
				dispatch('reload',{})
			}
		})
	}
}
